package com.lincoln.framework.service;

import com.lincoln.framework.entity.BaseEntity;
import com.lincoln.framework.hibernate.Page;
import com.lincoln.framework.hibernate.SimpleHibernateTemplate;
import com.lincoln.framework.utils.StringUtilsEx;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Lincoln on 2017/10/18.
 */
public abstract class BaseService<T extends BaseEntity> {
    public SimpleHibernateTemplate<T, Long> dao;

    public abstract void setSessionFactory(SessionFactory sessionFactory);

    /**
     * 创建分页条件Criteria
     */
    public Criteria createCriteria(Criteria criteria, Map<String, Object> parameters) {
        for (String key : parameters.keySet()) {
            if (parameters.get(key) != null) {
                criteria.add(Restrictions.eq(key, parameters.get(key)));
            }
        }
        return criteria;
    }

    public List<T> findAll() {
        Criteria criteria = this.dao.createCriteria();
        return findList(criteria);
    }

    /**
     * 查询分页
     */
    public Page<T> findPage(Page<T> page) {
        Criteria criteria = this.dao.createCriteria();
        criteria = createCriteria(criteria, page.getQueryMap());
        page = dao.findByCriteria(page, criteria);
        return page;
    }

    /**
     * 查询分页list
     *
     * @param criteria
     * @return
     */
    public List<T> findList(Criteria criteria) {
        return this.dao.findByCriteria(criteria);
    }

    /**
     * 根据id查询
     */
    public T getById(long id) {
        return this.dao.get(id);
    }

    /**
     * 保存
     */
    public void save(T t) {
        if (t.getCreateTime() == null) {
            t.setCreateTime(new Date());
        }
        t.setUpdateTime(new Date());
        this.dao.save(t);
    }

    /**
     * 保存
     */
    public void saveOnly(T t) {
        if (t.getCreateTime() == null) {
            t.setCreateTime(new Date());
        }
        if (t.getUpdateTime() == null) {
            t.setUpdateTime(new Date());
        }
        this.dao.saveOnly(t);
    }

    /**
     * 删除
     */
    public void delete(T t) {
        this.dao.delete(t);
    }

    /**
     * 获取总数统计
     */
    public long getTotalCount() {
        try {
            return this.dao.findLong("select count(*) from" + T.entityName());
        } catch (Exception e) {
            return 0;
        }
    }
}
